package org.devocean.groupbuying.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.devocean.groupbuying.dao.MediaDAO;
import org.devocean.groupbuying.domain.Media;
import org.springframework.stereotype.Repository;


@Repository
public class MediaDAOImpl implements MediaDAO {

	@PersistenceContext
	private EntityManager em;
	public Media save(Media media) {
		em.persist(media);
		return media;
	}

	public List<Media> findMediaEntries(int firstResult, int maxResults) {
		return em.createQuery("SELECT m  FROM Media m", Media.class)
				.setFirstResult(firstResult).setMaxResults(maxResults)
				.getResultList();
	}

	public long countMedia() {
		return em.createQuery("SELECT COUNT(m)  FROM Media m", Long.class)
				.getSingleResult();
	}

	public Boolean delete(Media media) {
		try {
			em.remove(media);
			return true;
		} catch (Exception e) {
			return false;
		}

	}

	public Media findMediaById(Integer id) {
		Media media = em.find(Media.class, id);
		return media;
	}


	public Media update(Media media) {
		Media merged = em.merge(media);
		return merged;
	}

	public List<Media> findMediaByTitle(String searchText) {
		return em.createQuery("SELECT m  FROM Media m where m.title like :criteria", Media.class).setParameter("criteria", searchText+"%")
				.getResultList();
	}

}
